<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  title: ''
})
// ----
let forSortNum = 0
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取合作商家分类信息--
  const forCateData = { params: { 'CommonTypeSearch[id]': proxy.$route.query.id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('common-type/index', forCateData)
  ]).then(proxy.$Axios.spread((cateData) => {
    const CData = cateData.items[0] || {}
    user.title = proxy.$Myfun.setText(CData.name)
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 5,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'program/index',
    forData: {
      params: {
        'ProgramSearch[dealer_id]': logUser.id,
        'ProgramSearch[common_type_id]': proxy.$route.query.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    if (Number(pageNum) === 1 && Number(res.items.length) > 0) forSortNum = res.items[0].sort_num
    // ----
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forIcons = []
    await proxy.$Myfun.getJsonData(item.icon, (resJson) => {
      if (Number(resJson.length) > 0) forIcons = resJson
    })
    // ----
    let forImgs = []
    await proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
      if (Number(resJson.length) > 0) forImgs = resJson
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      icons: forIcons,
      imgs: forImgs,
      isOpenExten: Number(item.is_extension) === 1,
      // ----
      sortNum: forSortNum
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'PromoteDescAdm', { id: item.id })
      break
    }
    case 2: {
      proxy.$Myfun.openPage(proxy, 'push', 'PromoteShare', { id: item.id })
      break
    }
    case 3: {
      proxy.$Myfun.openPage(proxy, 'push', 'PromoteListAdm', { id: item.id })
      break
    }
    case 4: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            // ----
            const opts = {
              region: proxy.$Global.aoss.region,
              bucket: proxy.$Global.aoss.bucket,
              accessKeyId: proxy.$Global.aoss.accessKeyId,
              accessKeySecret: proxy.$Global.aoss.accessKeySecret
            }
            if (Number(item.icons.length) > 0) {
              const imgArr = item.icons
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            if (Number(item.imgs.length) > 0) {
              const imgArr = item.imgs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            // ----
            await proxy.$http.delete('program/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 5: {
      proxy.$http.patch('program/update?id=' + item.id, {
        sort_num: Number(item.sortNum + 1),
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        mescroll.scrollTo(0)
        mescroll.resetUpScroll()
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
    case 6: {
      let forOpen = true
      let forCurState = 1
      if (item.isOpenExten) {
        forOpen = false
        forCurState = 0
      }
      // ----
      proxy.$http.patch('program/update?id=' + item.id, {
        is_extension: forCurState,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        item.isOpenExten = forOpen
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-plan xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LPN-title">{{item.name}}</div>
            <div class="LPN-con">
              <a class="xw-Bfg xw-flex xw-flex-align" @click="getAuditFun(1, item)">
                <div class="LPN-item xw-flex-W1">推广佣金</div>
                <i class="fal fa-angle-right"></i>
              </a>
              <a class="xw-Bfg xw-flex xw-flex-align" @click="getAuditFun(2, item)">
                <div class="LPN-item xw-flex-W1">预览分享</div>
                <i class="fal fa-angle-right"></i>
              </a>
            </div>
            <div class="LPN-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn xw-WBlue" @click="getAuditFun(3, item)">修改</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(4, item)">删除</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(5, item)">置顶</div>
              <div class="LPN-check xw-flex xw-flex-align">
                <span>推广</span>
                <div class="USS-check" @click="getAuditFun(6, item)"><input type="checkbox" class="a-switch" v-model="item.isOpenExten"/><label></label></div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-plan li { position: relative; margin: 1rem 1rem 0; padding: 0 1rem; overflow: hidden; }
.LPN-title { padding: 1rem 0 0; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.LPN-con { overflow: visible; }
.LPN-con i { font-size: 2.4rem; color: #bbbbbb; }
.LPN-item { padding: 1rem 0; font-size: 1.5rem; }
.LPN-btns { padding: 1rem 0; overflow: visible; }
.LPN-check { overflow: visible; }
.LPN-check div { overflow: visible; }
</style>
